<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Admin\Controller;

/**
 * Description of MwsController
 *
 * @author zhouyehao
 */
class MwsOrderController extends AdminController {

    protected $model = null;
    //当前登录管理员所有子节点组别
    protected $childrenIds = [];
    protected $serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
    protected $awsAccessKeyId = 'AKIAJV6ZBRFUMZR4PQBA';
    protected $sellerId = 'AFM3VFC9BYR23';
    protected $secretKey = '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';
    protected $marketplaceId = 'ATVPDKIKX0DER';
    protected $applicationName = 'XiangKe';
    protected $applicationVersion = '1.0';
    protected $mwsConfig = array(
        'ServiceURL' => 'https://mws.amazonservices.com/Orders/2013-09-01',
        'ProxyHost' => null,
        'ProxyPort' => -1,
        'ProxyUsername' => null,
        'ProxyPassword' => null,
        'MaxErrorRetry' => 3,
    );

    // North America:
    // $serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
    // Europe
    //$serviceUrl = "https://mws-eu.amazonservices.com/Orders/2013-09-01";
    // Japan
    //$serviceUrl = "https://mws.amazonservices.jp/Orders/2013-09-01";
    // China
    //$serviceUrl = "https://mws.amazonservices.com.cn/Orders/2013-09-01";

    public function _initialize() {
        vendor('MarketplaceWebServiceOrders.Samples.config', '', '.php');

        parent::_initialize();
    }

    public function test() {


        $amazonOrderId = '114-1438982-4829000';
        $item = $this->getOrderItem($amazonOrderId);

        $items = $item['ListOrderItemsResult']['OrderItems']['OrderItem'];

        if (isset($item['ListOrderItemsResult']['OrderItems']['OrderItem']['ASIN'])) {
            echo 123;
            die;
        } else {
            echo 222;
            die;
        }

        foreach ($items as $row) {
            if (!isset($row['OrderItemId'])) {
                continue;
            }
            $orderItemId = $row['OrderItemId'];
            $res = M('MwsOrderItems')->where(array('order_item_id' => $orderItemId))->find();
            $row = $this->formatOrderItem($row);
            dump($row);
            die;
            if (empty($row['order_item_id'])) {
                continue;
            }
            $row['amazon_order_id'] = $amazonOrderId;
            if ($res) {
                $row['updatetime'] = date('Y-m-d H:i:s', time());
                unset($row['order_item_id']);
                M('MwsOrderItems')->where(array('order_item_id' => $orderItemId))->save($row);
            } else {
                M('MwsOrderItems')->add($row);
                $num++;
            }
        }

//        $date = 
//        dump($this->getOrderList($date));
    }

    public function getMwsOrder() {
        $start_date = I('start_time');
        $end_date = I('end_time');
//        $start_date = gmdate("Y-m-d\TH:i:s\Z", strtotime('2017-11-10') - 3600 * 24);
//        $end_date = gmdate("Y-m-d\TH:i:s\Z", strtotime('2017-11-10'));
        $createdAfter = gmdate("Y-m-d\TH:i:s\Z", strtotime($start_date));
        $createdBefore = gmdate("Y-m-d\TH:i:s\Z", strtotime($end_date));

        $data = $this->getOrderList($createdAfter, $createdBefore);
        if (!empty($data)) {
            $nextToken = '';
            if (isset($data['ListOrdersResult']['NextToken'])) {
                $nextToken = $data['ListOrdersResult']['NextToken'];
            }
            $fristData = $data['ListOrdersResult'];
            $num = $this->saveOrder($fristData);
            while ($nextToken) {
                $next = $this->getNextOrderList($nextToken);
                $nextData = $next['ListOrdersByNextTokenResult'];
                $num += $this->saveOrder($nextData);
                if (isset($next['ListOrdersByNextTokenResult']['NextToken'])) {
                    $nextToken = $next['ListOrdersByNextTokenResult']['NextToken'];
                } else {
                    $nextToken = '';
                }
            }

            if ($num) {
                $this->ajaxSuccess('成功获取' . $num . '条数据');
            }
        }

        $this->ajaxError('获取失败');
    }

    //请求数据
    private function invokeData(\MarketplaceWebServiceOrders_Interface $service, $request, $action) {
        try {
            $response = $service->$action($request);
//            $response = $service->listOrders($request);
            $dom = new \DOMDocument();
            $dom->loadXML($response->toXML());
            $dom->preserveWhiteSpace = false;
            $dom->formatOutput = true;
            return $dom->saveXML();
        } catch (\MarketplaceWebServiceOrders_Exception $ex) {
            return FALSE;
        }
    }

    public function getSkuStock() {
        vendor('FBAInventoryServiceMWS.Client', '', '.php');
        vendor('FBAInventoryServiceMWS.Model.ListInventorySupplyRequest', '', '.php');
        $service = new \FBAInventoryServiceMWS_Client($this->awsAccessKeyId, $this->secretKey, $this->applicationName, $this->applicationVersion, $this->mwsConfig);
        $request = new \FBAInventoryServiceMWS_Model_ListInventorySupplyRequest();

        $request->setSellerSkus('A311_Silver_S');
        $request->setMarketplaceId($this->marketplaceId);

        $xmlinfo = $this->invokeDataByInventory($service, $request, 'listInventorySupply');
        if ($xmlinfo) {
            $list = $this->xmlToArray($xmlinfo);
//            Log::write($list, 'info', true);
            return $list;
        } else {
            return [];
        }
    }

    /**
     * 获取订单
     */
    public function getOrderList($createdAfter, $createdBefore = '', $orderStatus = 'Shipped') {

        if (empty($createdAfter)) {
            return [];
        }

        vendor('MarketplaceWebServiceOrders.Client', '', '.php');
        vendor('MarketplaceWebServiceOrders.Model.ListOrdersRequest', '', '.php');
        $service = new \MarketplaceWebServiceOrders_Client($this->awsAccessKeyId, $this->secretKey, $this->applicationName, $this->applicationVersion, $this->mwsConfig);
        $request = new \MarketplaceWebServiceOrders_Model_ListOrdersRequest();
        $request->setSellerId($this->sellerId);
        $request->setMarketplaceId($this->marketplaceId);
        $request->setOrderStatus($orderStatus);
        $request->setCreatedAfter($createdAfter);

        if ($createdBefore) {
            $request->setCreatedBefore($createdBefore);
        }
        $xmlinfo = $this->invokeData($service, $request, 'ListOrders');
        if ($xmlinfo) {
            $list = $this->xmlToArray($xmlinfo);
//            Log::write($list, 'info', true);
            return $list;
        } else {
            return [];
        }
    }

    /**
     * 获取下一页订单
     */
    public function getNextOrderList($nextToken) {

        vendor('MarketplaceWebServiceOrders.Client', '', '.php');
        vendor('MarketplaceWebServiceOrders.Model.ListOrdersByNextTokenRequest', '', '.php');

        $service = new \MarketplaceWebServiceOrders_Client($this->awsAccessKeyId, $this->secretKey, $this->applicationName, $this->applicationVersion, $this->mwsConfig);
        $request = new \MarketplaceWebServiceOrders_Model_ListOrdersByNextTokenRequest();
        $request->setSellerId($this->sellerId);
        $request->setNextToken($nextToken);
        $xmlinfo = $this->invokeData($service, $request, 'ListOrdersByNextToken');
        if ($xmlinfo) {
            $list = $this->xmlToArray($xmlinfo);
//            Log::write($list, 'info', true);
            return $list;
        } else {
            return [];
        }
    }

    public function getOrderItem($order_id) {

        vendor('MarketplaceWebServiceOrders.Client', '', '.php');
        vendor('MarketplaceWebServiceOrders.Model.ListOrderItemsRequest', '', '.php');

        $service = new \MarketplaceWebServiceOrders_Client($this->awsAccessKeyId, $this->secretKey, $this->applicationName, $this->applicationVersion, $this->mwsConfig);
        $request = new \MarketplaceWebServiceOrders_Model_ListOrderItemsRequest();
        $request->setSellerId($this->sellerId);
        $request->setAmazonOrderId($order_id);
        $xmlinfo = $this->invokeData($service, $request, 'ListOrderItems');
        if ($xmlinfo) {
            $list = $this->xmlToArray($xmlinfo);
//            Log::write($list, 'info', true);
            return $list;
        } else {
            return [];
        }
    }

    //xml转换成数组
    public function xmlToArray($data) {
        return json_decode(json_encode((array) simplexml_load_string($data)), true);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////
    //将亚马逊API获取的订单格式转换成可以直接存入数据库的格式
    public function formatOrder($order) {
        if (empty($order)) {
            return [];
        }
        $tmp = [];

        $tmp['amazon_order_id'] = $order['AmazonOrderId'];
        $tmp['seller_order_id'] = $order['SellerOrderId'];
        $tmp['order_status'] = $order['OrderStatus'];
        $tmp['fulfillment_channel'] = $order['FulfillmentChannel'];
        $tmp['sales_channel'] = $order['SalesChannel'];
        $tmp['ship_service_level'] = $order['ShipServiceLevel'];
        $tmp['number_of_items_shipped'] = $order['NumberOfItemsShipped'];
        $tmp['number_of_items_unshipped'] = $order['NumberOfItemsUnshipped'];
        $tmp['payment_method'] = $order['PaymentMethod'];
        $tmp['marketplace_id'] = $order['MarketplaceId'];
        $tmp['buyer_email'] = $order['BuyerEmail'];
        $tmp['buyer_name'] = $order['BuyerName'];
        $tmp['shipment_service_level_category'] = $order['ShipmentServiceLevelCategory'];
        $tmp['order_type'] = $order['OrderType'];

        if ($order['IsBusinessOrder'] != 'false') {
            $tmp['is_business_order'] = 1;
        }

        if ($order['IsPrime'] != 'false') {
            $tmp['is_prime'] = 1;
        }

        if ($order['IsPremiumOrder'] != 'false') {
            $tmp['is_premium_order'] = 1;
        }

        if ($order['IsReplacementOrder'] != 'false') {
            $tmp['is_replacement_order'] = 1;
        }


        //时间转换
        $tmp['purchase_date'] = $this->usaDateToCn($order['PurchaseDate']);
        $tmp['last_update_date'] = $this->usaDateToCn($order['LastUpdateDate']);
        $tmp['earliest_ship_date'] = $this->usaDateToCn($order['EarliestShipDate']);
        $tmp['latest_ship_date'] = $this->usaDateToCn($order['LatestShipDate']);


        if (isset($order['EarliestDeliveryDate'])) {
            $tmp['earliest_delivery_date'] = $this->usaDateToCn($order['EarliestDeliveryDate']);
        }

        if (isset($order['LatestDeliveryDate'])) {
            $tmp['latest_delivery_date'] = $this->usaDateToCn($order['LatestDeliveryDate']);
        }

        //json 存储
        $tmp['shipping_address'] = json_encode($order['ShippingAddress']);
        $tmp['payment_execution_detail'] = json_encode($order['PaymentExecutionDetail']);
        $tmp['payment_method_details'] = json_encode($order['PaymentMethodDetails']);

        //价格
        $tmp['currency_code'] = $order['OrderTotal']['CurrencyCode'];
        $tmp['order_total'] = $order['OrderTotal']['Amount'];
        $tmp['uid'] = $this->auth->id;


        return $tmp;
    }

    public function formatOrderItem($item) {
        if (empty($item)) {
            return [];
        }
        $tmp = [];

        $tmp['amazon_order_id'] = $item['AmazonOrderId'];
        $tmp['ASIN'] = $item['ASIN'];
        $tmp['seller_sku'] = $item['SellerSKU'];
        $tmp['order_item_id'] = $item['OrderItemId'];
        $tmp['title'] = $item['Title'];
        $tmp['quantity_ordered'] = $item['QuantityOrdered'];
        $tmp['quantity_shipped'] = $item['QuantityShipped'];
        $tmp['condition_id'] = $item['ConditionId'];
        $tmp['condition_subtype_id'] = $item['ConditionSubtypeId'];

        if (isset($item['ItemPrice'])) {
            $tmp['item_price'] = $item['ItemPrice']['Amount'];
        }
        if (isset($item['ShippingPrice'])) {
            $tmp['shipping_price'] = $item['ShippingPrice']['Amount'];
        }
        if (isset($item['GiftWrapPrice'])) {
            $tmp['gift_wrap_price'] = $item['GiftWrapPrice']['Amount'];
        }
        if (isset($item['ItemTax'])) {
            $tmp['item_tax'] = $item['ItemTax']['Amount'];
        }
        if (isset($item['ShippingTax'])) {
            $tmp['shipping_tax'] = $item['ShippingTax']['Amount'];
        }
        if (isset($item['GiftWrapTax'])) {
            $tmp['gift_wrap_tax'] = $item['GiftWrapTax']['Amount'];
        }
        if (isset($item['ShippingDiscount'])) {
            $tmp['shipping_discount'] = $item['ShippingDiscount']['Amount'];
        }
        if (isset($item['PromotionDiscount'])) {
            $tmp['promotion_discount'] = $item['PromotionDiscount']['Amount'];
        }

        if (isset($item['PromotionIds'])) {
            $tmp['promotion_ids'] = json_encode($item['PromotionIds']);
        }

        return $tmp;
    }

    //美国时间转换成中国时间
    public function usaDateToCn($date) {
        return date('Y-m-d H:i:s', strtotime($date));
    }

    public function saveOrder($data) {
        $order = $data['Orders']['Order'];

        $num = 0;
        foreach ($order as $val) {
            M()->startTrans();
            try {
                $amazonOrderId = $val['AmazonOrderId'];
                $res = M('MwsOrders')->where(array('amazon_order_id' => $amazonOrderId))->find();
                $val = $this->formatOrder($val);
//                    dump($val);die;
                if ($res) {
                    unset($val['amazon_order_id']);
                    $val['updatetime'] = date('Y-m-d H:i:s', time());
                    M('MwsOrders')->where(array('amazon_order_id' => $amazonOrderId))->save($val);
                } else {
                    M('MwsOrders')->add($val);
                    $num++;
                }
                //获取订单详情
                $item = $this->getOrderItem($amazonOrderId);
                $items = $item['ListOrderItemsResult']['OrderItems']['OrderItem'];
                if (isset($item['ListOrderItemsResult']['OrderItems']['OrderItem']['ASIN'])) {
                    if (!isset($items['OrderItemId'])) {
                        continue;
                    }
                    $orderItemId = $items['OrderItemId'];
                    $res = M('MwsOrderItems')->where(array('order_item_id' => $orderItemId))->find();
                    $items = $this->formatOrderItem($items);
                    if (empty($items['order_item_id'])) {
                        continue;
                    }
                    $items['amazon_order_id'] = $amazonOrderId;
                    if ($res) {
                        $items['updatetime'] = date('Y-m-d H:i:s', time());
                        unset($items['order_item_id']);
                        M('MwsOrderItems')->where(array('order_item_id' => $orderItemId))->save($items);
                    } else {
                        M('MwsOrderItems')->add($items);
                    }
                } else {
                    foreach ($items as $row) {
                        if (!isset($row['OrderItemId'])) {
                            continue;
                        }
                        $orderItemId = $row['OrderItemId'];
                        $res = M('MwsOrderItems')->where(array('order_item_id' => $orderItemId))->find();
                        $row = $this->formatOrderItem($row);
                        if (empty($row['order_item_id'])) {
                            continue;
                        }
                        $row['amazon_order_id'] = $amazonOrderId;
                        if ($res) {
                            $row['updatetime'] = date('Y-m-d H:i:s', time());
                            unset($row['order_item_id']);
                            M('MwsOrderItems')->where(array('order_item_id' => $orderItemId))->save($row);
                        } else {
                            M('MwsOrderItems')->add($row);
                        }
                    }
                }

                M()->commit();
            } catch (\Exception $e) {
                // 回滚事务
                M()->rollback();
                return 0;
            }
        }
        return $num;
    }

}
